package lev01_beginnerClass.class06_binarySortFind;

import lev01_beginnerClass.util.HelpUtil;

import java.util.Arrays;

/**
 * find left most target num in orderd arrray
 */
public class L02_FindLeftMostTargetInOrderArray {

    public static void main(String[] args) {
        int maxTestTime = 3000;
        boolean succeed = true;
        for(int i = 0;i < maxTestTime;i++){
            int maxLen = 20;
            int maxValue = 100;
            int[] arr = HelpUtil.generateRandomArr(20, 100);
            Arrays.sort(arr);
            int targetNum = (int) (Math.random()*101);
            if(forTest(arr,targetNum) != findLeftMostNoLessTarget(arr,targetNum)){
                System.out.println(Arrays.toString(arr));
                System.out.println(targetNum);
                System.out.println(forTest(arr,targetNum));
                System.out.println(findLeftMostNoLessTarget(arr,targetNum));
                succeed = false;
                break;
            }
        }
        System.out.println(succeed? "nice":"fuck");
    }

    /**
     * find leftmost more than target num in ordered array
     *
     * @param arr    ordered array
     * @param target taget num
     * @return
     */
    public static int findLeftMostNoLessTarget(int[] arr, int target) {
        //give priority to boundary condition
        if (arr == null || arr.length == 0) {
            return -1;
        }
        //def left and right bound
        int left = 0;
        int right = arr.length - 1;
        //def result
        int ans = -1;
        while (left <= right) {
            int mid = left + ((right - left) >> 1);
            if (arr[mid] >= target) {
                ans = mid;
                right = mid - 1;
            } else {
                left = mid + 1;
            }
        }
        return ans;
    }

    /**
     * For test
     *
     * @param arr    ordered arr
     * @param target target num
     * @return
     */
    public static int forTest(int[] arr, int target) {
        for(int i = 0; i< arr.length;i++){
            if(arr[i] >= target){
                return i;
            }
        }
        return -1;
    }


}
